<?php

require_once __DIR__.'/vendor/autoload.php';

// 加载环境变量
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// 创建数据库连接
try {
    $pdo = new PDO(
        "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']};charset=utf8mb4",
        $_ENV['DB_USERNAME'],
        $_ENV['DB_PASSWORD'],
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );

    echo "✅ 数据库连接成功\n";

    // 检查是否已存在admin用户
    $existingResult = $pdo->query("SELECT COUNT(*) as count FROM users WHERE username = 'admin'");
    $existing = $existingResult->fetch();

    if ($existing['count'] > 0) {
        echo "ℹ️ admin用户已存在\n";
        exit(0);
    }

    // 创建admin用户
    $password = password_hash('admin123', PASSWORD_DEFAULT); // 默认密码：admin123

    $stmt = $pdo->prepare("
        INSERT INTO users (
            username, phone, password, status, created_at, updated_at
        ) VALUES (?, ?, ?, 'active', NOW(), NOW())
    ");

    $stmt->execute(['admin', '13800000000', $password]);
    $userId = $pdo->lastInsertId();

    echo "✅ 成功创建admin用户 (ID: {$userId})\n";
    echo "用户名: admin\n";
    echo "密码: admin123\n";
    echo "手机号: 13800000000\n";

    // 为admin用户分配超级管理员角色
    $roleResult = $pdo->query("SELECT id FROM roles WHERE code = 'super_admin'");
    $role = $roleResult->fetch();

    if ($role) {
        $roleStmt = $pdo->prepare("
            INSERT INTO user_roles (user_id, role_id, created_at, updated_at)
            VALUES (?, ?, NOW(), NOW())
        ");
        $roleStmt->execute([$userId, $role['id']]);
        echo "✅ 已为admin用户分配超级管理员角色\n";
    } else {
        echo "⚠️ 未找到超级管理员角色，请稍后手动分配\n";
    }

    echo "\n🎉 admin用户创建完成！\n";
    echo "您现在可以使用以下凭据登录：\n";
    echo "用户名: admin\n";
    echo "密码: admin123\n";

} catch (Exception $e) {
    echo "❌ 错误: " . $e->getMessage() . "\n";
}
